package com.pjhouse.module.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.citrus.service.uribroker.URIBrokerService;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.TurbineRunData;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.google.common.base.Strings;
import com.pjhouse.core.common.domain.Result;
import com.pjhouse.core.user.domain.UserDTO;
import com.pjhouse.core.user.service.UserService;
import com.pjhouse.pipeline.context.CookieUtil;

public class LoginAction {

	@Resource
	private UserService userService;
	@Resource
	protected URIBrokerService uriBrokerService;
	
	public void doLogin(
			@Param("phone") final String phone,
			@Param("password") final String password,
			HttpServletResponse response,
			Context context, TurbineRunData rundata){
		if(Strings.isNullOrEmpty(phone)){
			context.put("message", "请输入账号");
			return ;
		}
		context.put("phone", phone);
		if(Strings.isNullOrEmpty(password)){
			context.put("message", "请输入密码");
			return ;
		}
		context.put("password", password);
		
		Result<UserDTO> userResult = userService.getByPhone(phone);
		if(userResult.isFailure()){
			context.put("message", userResult.getErrorMessage());
			return ;
		}
		if(userResult.getValue() == null){
			context.put("message", "对应用户不存在");
			return ;
		}
		UserDTO user = userResult.getValue();
		if(!user.getPassword().equals(password)){
			context.put("message", "密码错误");
			return ;
		}
		CookieUtil.setCookie(response, user);
		rundata.setRedirectLocation(uriBrokerService.getURIBroker("rootModule").render() + "/index.htm");
	}
}
